package com.lanhai.agv;

import java.util.List;

import com.lanhai.agv.dispatch.AgvEventThread;
import com.lanhai.agv.dispatch.DispatchEventThread;
import com.lanhai.agv.dispatch.StationEventThread;
import com.lanhai.agv.listener.AgvListener;
import com.lanhai.agv.listener.HackListener;
import com.lanhai.agv.listener.StationListener;
import com.lanhai.agv.listener.ThirdListener;
import com.lanhai.agv.log.LogThread;
import com.lanhai.agv.push.MsgPushThread;
import com.lanhai.agv.push.ThirdHeartThread;

/**
 * 整个调度事件的核心
 * 
 * @author virus408
 *
 */
public class DispatchCore {
	
	MsgPushThread push;

	AgvEventThread agvEvent;
	StationEventThread stationEvent;
	DispatchEventThread dispatchEvent;

	AgvListener agvListener;
	HackListener hackListener;
	StationListener[] stationListener;
ThirdListener thirdListener;
	
	ThirdHeartThread heartListener;
	LogThread logThread;
	Config conf;

	public DispatchCore(Config cc) {
		conf = cc;
	}

	/**
	 * 初始侦听器
	 */
	void initListener() {
		agvListener = new AgvListener();
		agvListener.Start(conf.getAgvListenerPort());
		
		hackListener=new HackListener();
		hackListener.Start(conf.getHackListenerPort());

		List<Integer> ps = conf.getStationListenerPort();
		if(ps.size()>0) {
			stationListener = new StationListener[ps.size()];
			for (int i = 0; i < ps.size(); i++) {
				stationListener[i] = new StationListener();
				stationListener[i].Start(ps.get(i));
			}
		}
		
		
		thirdListener=new ThirdListener();
		thirdListener.Start(conf.getThirdJumpLitenerPort());
	}

	/**
	 * 初始处理线程
	 */
	void initEventThread() {
		agvEvent = new AgvEventThread();
		stationEvent = new StationEventThread();
		dispatchEvent = new DispatchEventThread();

		agvEvent.Start(conf.getAgvEventThreadNum());
		stationEvent.Start(conf.getStationEventThreadNum());
		dispatchEvent.Start(conf.getDispatchEventThreadNum());
		
		logThread=new LogThread(conf);
		logThread.Start( );
	}

	/**
	 * 初始推送
	 */
	void initPush() {
		push = new MsgPushThread();
		push.Start(conf.getMsgSendThreadNum());
		
		heartListener=new ThirdHeartThread();
		heartListener.Start(conf.getThirdJumpIP(), conf.getThirdJumpPort());
	}
	
	public void Start() {
	
		initListener();
		System.out.println("侦听模块启动成功" );
		initPush();
		System.out.println("调度指令模块启动成功" );
		initEventThread();
		System.out.println("事件处理模块启动成功" );
	}
	
	public void Stop() {
		agvListener.Stop();
		hackListener.Stop();
		thirdListener.Stop();
		if(stationListener!=null&&stationListener.length>0) {
			int k=stationListener.length;
			for (int i = 0; i < k; i++) { 
				stationListener[i].Stop();
			}
		}
		System.out.println("侦听模块已停止" );
		
		agvEvent.Stop();
		stationEvent.Stop();
		dispatchEvent.Stop();
		System.out.println("事件处理模块已停止" );
		
		push.Stop();
		heartListener.Stop();
		logThread.Stop();
		System.out.println("调度指令模块已停止" );
	}
}
